import React, { Component } from 'react'

const IMG_SRC = require('static/images/naruto.png')

export default React.createClass({
  componentDidMount() {
    this.canvas = document.getElementById('canvas')
    this.context = canvas.getContext('2d')
    this.leftMargin = 0
    this.topMargin = 0
    this.image = new Image
    this.radius = 60
    // this.image.src = '../../statics/images/naruto.jpg'
    this.image.src = IMG_SRC
    const box = document.querySelector('.canvas-box')
    const img = document.querySelector('.canvas-box img')
    this.image.onload = () => {
      this.canvas.width = this.image.width
      this.canvas.height = this.image.height
      box.style.setProperty('width', `${this.canvas.width}px`)
      box.style.setProperty('height', `${this.canvas.height}px`)
      img.style.setProperty('width', `${this.image.width}px`)
      img.style.setProperty('height', `${this.image.height}px`)
      this.leftMargin = this.image.width / 2 - this.canvas.width - 2
      this.topMargin = this.image.height / 2 - this.canvas.height - 2
      img.style.setProperty('top', `-${this.topMargin}px`)
      img.style.setProperty('left', `-${this.leftMargin}px`)
      this.initCanvas()
    }
  },
  render() {
    return (
      <div className={`rt-CanvasBlurImg-container`}>
        <div className={`canvas-box`}>
          <canvas id="canvas"></canvas>
          <img
            alt="naruto" src={IMG_SRC}
          />
          <span className={`-reset-btn`} onClick={this.reset}>RESET</span>
          <span className={`-show-btn`} onClick={this.show}>SHOW</span>
        </div>
      </div>
    )
  },
  initCanvas() {
    this.clipRegion = {
      x: Math.random() * (this.canvas.width - 2 * this.radius) + this.radius,
      y: Math.random() * (this.canvas.height - 2 * this.radius) + this.radius,
      r: this.radius,
    }
    this.draw()
  },
  draw() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
    this.context.save()
    this.setClipRegion()
    this.context.drawImage(this.image, 0, 0)
    this.context.restore()
  },
  setClipRegion() {
    this.context.beginPath()
    const { x, y, r } = this.clipRegion
    this.context.arc(x, y, r, 0, Math.PI * 2)
    this.context.clip()
  },
  show() {
    clearInterval(this.theAnimation)
    this.theAnimation = setInterval(() => {
      console.log('interval')
      this.clipRegion.r += 20
      this.draw()
      if (this.clipRegion.r > 2 * Math.max(this.canvas.width, this.canvas.height)) {
        clearInterval(this.theAnimation)
      }
    }, 30)
  },
  reset() {
    clearInterval(this.theAnimation)
    this.initCanvas()
  }
})